package me.zhengjie.tools.rest

import me.zhengjie.logging.annotation.Log
import me.zhengjie.tools.service.dto.LocalStorageQueryCriteria
import me.zhengjie.tools.service.LocalStorageService
import me.zhengjie.tools.domain.LocalStorage
import io.swagger.v3.oas.annotations.media.Schema
import jakarta.servlet.http.HttpServletResponse
import org.springframework.data.domain.Pageable
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile
import java.io.IOException

/**
 * @author Kuki Wu
 * @date 2019-09-05
 */
@Schema(description = "工具：本地存储管理")
@RestController
@RequestMapping("/api/localStorage")
class LocalStorageController(private val localStorageService: LocalStorageService) {
    @Schema(description = "查询文件")
    @GetMapping
    @PreAuthorize("@el.check('storage:list')")
    fun getLocalStorages(criteria: LocalStorageQueryCriteria, pageable: Pageable?): ResponseEntity<*> {
        return ResponseEntity<Any?>(localStorageService.queryAll(criteria, pageable), HttpStatus.OK)
    }

    @Log("导出数据")
    @Schema(description = "导出数据")
    @GetMapping(value = ["/download"])
    @PreAuthorize("@el.check('storage:list')")
    @Throws(
        IOException::class
    )
    fun download(response: HttpServletResponse?, criteria: LocalStorageQueryCriteria) {
        localStorageService.download(localStorageService.queryAll(criteria), response)
    }

    @Schema(description = "上传文件")
    @PostMapping
    @PreAuthorize("@el.check('storage:add')")
    fun create(@RequestParam name: String?, @RequestParam("file") file: MultipartFile): ResponseEntity<*> {
        return ResponseEntity<Any?>(localStorageService.create(name, file), HttpStatus.CREATED)
    }

    @Schema(description = "修改文件")
    @PutMapping
    @PreAuthorize("@el.check('storage:edit')")
    fun update(@Validated @RequestBody resources: LocalStorage): ResponseEntity<*> {
        localStorageService.update(resources)
        return ResponseEntity<Any?>(HttpStatus.NO_CONTENT)
    }

    @Schema(description = "删除文件")
    @DeleteMapping(value = ["/{id}"])
    @PreAuthorize("@el.check('storage:del')")
    fun delete(@PathVariable id: Long): ResponseEntity<*> {
        localStorageService.delete(id)
        return ResponseEntity<Any?>(HttpStatus.OK)
    }

    @Log("多选删除")
    @DeleteMapping
    @Schema(description = "多选删除")
    fun deleteAll(@RequestBody ids: Array<Long>): ResponseEntity<*> {
        localStorageService.deleteAll(ids)
        return ResponseEntity<Any?>(HttpStatus.OK)
    }
}